package com.zjp.blog.controller.manage;

import com.zjp.blog.controller.BaseController;
import com.zjp.blog.controller.PagerBean;
import com.zjp.blog.controller.error.NotFoundException;
import com.zjp.blog.model.Article;
import com.zjp.blog.model.Tag;
import com.zjp.blog.service.ArticleService;
import com.zjp.blog.service.TagService;
import com.zjp.blog.service.support.ArticleQuery;
import com.zjp.blog.utils.Validation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author pj_zhong
 * @email pj_zhong@163.com / pj_zhong@gmail.com
 */

@Controller("")
@RequestMapping("/manage/tags")
public class TagController extends BaseController
{
    private static final Logger logger = LogManager.getLogger(TagController.class);
    private static String tagHome   = "/manage/tags/Home";
    private static String tagEdit   = "/manage/tags/tagEdit";
    private static String tagData = "/manage/tags/data";

    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleService articleService;

    @RequestMapping(method = RequestMethod.GET)
    public String tagHome(PagerBean<Tag> pager, ModelMap map)
    {
        return tagHome;
    }

    @RequestMapping(value = "load",method = RequestMethod.GET)
    public String load(String keyword,PagerBean<Tag> pager, Model map)
    {
        if(!Validation.isEmpty(keyword)) {
            logger.info("Searching:"+keyword);
            pager = tagService.getPage(keyword,pager);
        }else {
            pager = tagService.getPage(pager);
        }

        map.addAttribute("items",pager.getRecords());
        map.addAttribute("pager",pager);

        return tagData;
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    public String search(String keyword,PagerBean<Tag> pager,ModelMap map)
    {
        pager = tagService.getPage(keyword,pager);


        map.addAttribute("tags",pager.getRecords());
        map.addAttribute("pager",pager);

        return tagHome;
    }

    @RequestMapping(value="{id}")
    public String showPostByTag(@PathVariable String id, ModelMap map)
    {
        Tag tag = tagService.getById(Integer.parseInt(id));
        ArticleQuery query = new ArticleQuery();
        query.addTagId(tag.getId());

        List<Article> articles = articleService.search(query);

        map.addAttribute("tag",tag);
        map.addAttribute("items",articles);

        return ArticleController.ArticleHome;
    }

    @RequestMapping(value = "update",method = RequestMethod.GET)
    public String CreateOrUpdate(String id, ModelMap map)
    {
        if(!Validation.isEmpty(id)) {
            Tag tag = tagService.getById(Integer.parseInt(id));
            if (tag == null) {
                logger.error("Tag " + id + "Not found" );
                throw new NotFoundException("Tag " + id + "Not found");
            }

            logger.info("Updating:" + tag);
            map.addAttribute("tag",tag);
        }

        return tagEdit;
    }

    @RequestMapping(value = "update",method = RequestMethod.POST)
    public String CreateOrUpdate(Tag tag, RedirectAttributes redirectAttributes)
    {
        if(Validation.isEmpty(tag.getName())) return tagEdit;

        logger.info("Delete:" + tag);

        if(tag.getId()!=null) {
            tagService.Update(tag);
            addMessage(redirectAttributes,"Update Success");
        } else {
            tagService.Create(tag);
            addMessage(redirectAttributes,"Success");
        }

        return "redirect:/manage/tags";
    }

    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public String delete(@RequestParam("id")  String id, RedirectAttributes flushAttrs)
    {
        if(!Validation.isEmpty(id)) {
            tagService.deleteById(Integer.parseInt(id));
            addMessage(flushAttrs,"Delete Success");
        }else {
            addMessage(flushAttrs,"Delete fail");
        }

        return "redirect:/manage/tags";
    }

}
